package com.anjiplus.template.gaea.gateway.utils;

import com.alibaba.fastjson.JSONObject;
import com.anji.plus.gaea.bean.ResponseBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 网关工具类
 * @author lr
 * @since 2021-03-03
 */
public abstract class GaeaWebFluxUtils {

    /**
     * 用户名
     */
    public final static String USER_NAME = qualify("username");


    /**
     * 是否要跳过过滤器
     */
    public final static String SKIP = qualify("skip");

    private static String qualify(String attr) {
        return GaeaWebFluxUtils.class.getName() + "." + attr;
    }

    /**
     * 处理响应
     * @param exchange
     * @param code
     * @return
     */
    public static Mono<Void> getFilterResult(ServerWebExchange exchange, String code,String message){

        ResponseBean responseBean = ResponseBean.builder().code(code).message(message).build();
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        response.getHeaders().add("Accept", MediaType.APPLICATION_JSON_VALUE);

        String responseString = JSONObject.toJSONString(responseBean);
        DataBuffer wrap = exchange.getResponse().bufferFactory()
                .wrap(StringUtils.getBytes(responseString, StandardCharsets.UTF_8));
        //响应
        return response.writeWith(Mono.just(wrap));
    }
}
